package cn.mesmile.juc;

import lombok.Data;
import sun.reflect.generics.tree.Tree;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zb
 * @date 2021/9/2 14:38
 * @Description
 */
public class TestSort {

    // 住宅、车位、商业、办公
    public static void main(String[] args) {
        List<Home> homeList = new ArrayList<>();
        homeList.add(new Home("办公", 4));
        homeList.add(new Home("车位", 2));
        homeList.add(new Home("车位", 3));
        homeList.add(new Home("住宅", 1));
        homeList.add(new Home("住宅", 2));
        homeList.add(new Home("其他", 4));
        homeList.add(new Home("商业", 4));
        System.out.println("排序前 = " + homeList);

        List<String> sortList = Arrays.asList("住宅", "车位", "商业", "办公");
        // 自定义排序规则
        Comparator<String> comparator = (x,y) -> {
            if (x == null && y != null) {
                return 1;
            } else if (x != null && y == null) {
                return -1;
            } else if (x == null && y == null) {
                return -1;
            } else {
                //按照读取的list顺序排序
                for (String sort : sortList) {
                    if (sort.equals(x) || sort.equals(y)) {
                        if (x.equals(y)) {
                            return 0;
                        } else if (sort.equals(x)) {
                            return -1;
                        } else {
                            return 1;
                        }
                    }
                }
                return 0;
            }
        };

        List<Home> result = homeList.stream().sorted(Comparator.comparing(Home::getType, comparator)).collect(Collectors.toList());

        // 默认按照 key 升序排列
        Map<Integer, List<Home>> collect = homeList.stream().collect(Collectors.groupingBy(Home::getAge, TreeMap::new, Collectors.toList()));


        System.out.println("排序后 = " + result);
    }
}

@Data
class Home{
    // 按照这个字段排序
    public String type;

    public int age;

    public Home(String type,int age){
        this.type = type;
        this.age = age;
    }
}

